package com.bolt.report.engine.export;

import com.bolt.common.io.StringBufferWriter;
import com.bolt.common.io.StringBuilderWriter;
import com.bolt.report.engine.WriterExporterOutput;
import com.bolt.report.exception.ReportException;

import java.io.*;

public class SimpleWriterExporterOutput implements WriterExporterOutput {
    private final String encoding;
    private Writer writer;
    private boolean toClose;

    public SimpleWriterExporterOutput(StringBuffer sbuffer) {
        this.encoding = "UTF-8";

        if (sbuffer != null) {
            writer = new StringBufferWriter(sbuffer);
        }
    }


    public SimpleWriterExporterOutput(StringBuilder sbuilder) {
        this.encoding = "UTF-8";

        if (sbuilder != null) {
            writer = new StringBuilderWriter(sbuilder);
        }
    }


    public SimpleWriterExporterOutput(Writer writer) {
        this.encoding = "UTF-8";
        this.writer = writer;
        toClose = false;
    }


    public SimpleWriterExporterOutput(OutputStream outputStream) {
        this(outputStream, "UTF-8");
    }


    public SimpleWriterExporterOutput(OutputStream outputStream, String encoding) {
        this.encoding = encoding;
        if (outputStream != null) {
            try {
                writer = new OutputStreamWriter(outputStream, encoding);
            } catch (IOException e) {
                throw new ReportException(e);
            }
        }
        toClose = false;
    }


    public SimpleWriterExporterOutput(File file) {
        this(file, "UTF-8");
    }


    public SimpleWriterExporterOutput(File file, String encoding) {
        this.encoding = encoding;
        if (file != null) {
            try {
                OutputStream os = new FileOutputStream(file);
                writer = new OutputStreamWriter(os, encoding);
            } catch (IOException e) {
                throw new ReportException(e);
            }
        }
        toClose = true;
    }


    public SimpleWriterExporterOutput(String fileName) {
        this(fileName == null ? null : new File(fileName));
    }


    public SimpleWriterExporterOutput(String fileName, String encoding) {
        this(
                fileName == null ? null : new File(fileName),
                encoding
        );
    }


    @Override
    public String getEncoding() {
        return encoding;
    }


    @Override
    public Writer getWriter() {
        return writer;
    }


    @Override
    public void close() {
        if (toClose && writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}